package com.tanhua.api.impl.mongo;

import com.tanhua.api.mongo.VideoApi;
import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;


    @Override
    public PageBeanVo findVideo(Integer page, Integer pagesize) {

        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Video> list = mongoTemplate.find(query, Video.class);
        long count =mongoTemplate.count(query, Video.class);

        return new PageBeanVo(page,pagesize,count,list);
    }

    @Override
    public void save(Video vd) {
        vd.setCreated(System.currentTimeMillis());
        Long id = idService.getNextId("video");
        vd.setVid(id); //给大数据使用 （唯一且是数字）

        mongoTemplate.save(vd);

    }

    @Override
    public void saveFollowUser(FollowUser followUser) {
        mongoTemplate.insert(followUser);
    }

    @Override
    public void delete(Long id, Integer vid) {

        Query query = new Query(Criteria.where("userId").is(id).and("followUserId").is(vid));
        mongoTemplate.remove(query,"follow_user");
    }

    @Override
    public PageBeanVo findByvideos(Integer page, Integer pagesize, Long uid) {

        Query query = new Query(Criteria.where("userId").is(uid));
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);

        return new PageBeanVo(page,pagesize,count,videoList);
    }
    @Override
    public Video findById(String vid) {

        Video video = mongoTemplate.findById(vid, Video.class);
        return video;
    }
}
